package org.Lin.controller;

import org.Lin.model.FriendMessage;
import org.Lin.service.FriendMessageService;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.net.Socket;
import java.util.List;

public class MessageQueryController extends BaseController {

    private final FriendMessageService friendMessageService = new FriendMessageService();

    public void handleQueryMessages(JSONObject request, Socket socket) throws IOException {
        int senderId = request.getInt("sender_id");
        int receiverId = request.getInt("receiver_id");

        try {
            List<FriendMessage> messages = friendMessageService.getMessagesBetween(senderId, receiverId);
            JSONArray array = new JSONArray();
            for (FriendMessage msg : messages) {
                JSONObject jsonMsg = new JSONObject();
                jsonMsg.put("sender_id", msg.getSenderId());
                jsonMsg.put("receiver_id", msg.getReceiverId());
                jsonMsg.put("message_data", msg.getMessageData());
                jsonMsg.put("sent_time", msg.getSentTime().toString());
                jsonMsg.put("message_status", msg.getMessageStatus());
                array.put(jsonMsg);
            }

            JSONObject response = new JSONObject();
            response.put("type", "query_messages");
            response.put("messages", array);
            sendResponse(socket, response);
        } catch (Exception e) {
            e.printStackTrace();
            sendResponse(socket, createErrorResponse("查询失败"));
        }
    }

    private void sendResponse(Socket socket, JSONObject response) throws IOException {
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.println(response.toString());
    }
}
